package com.cch.cooperation.api.auth.interceptors;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cch.cooperation.api.auth.dto.LoginUserDTO;
import com.cch.cooperation.api.auth.dto.UserDeviceDTO;
import com.cch.cooperation.api.auth.service.UserDeviceServiceImpl;
import com.cch.cooperation.common.web.session.Session;
import com.cch.cooperation.common.web.session.SessionManager;
import com.cch.cooperation.common.web.util.RequestUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserDeviceInterceptor implements HandlerInterceptor {

    private UserDeviceServiceImpl userDeviceService;
    private SessionManager sessionManager;

    public UserDeviceInterceptor(SessionManager sessionManager, UserDeviceServiceImpl userDeviceService) {
        this.sessionManager = sessionManager;
        this.userDeviceService = userDeviceService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Session<LoginUserDTO> session = sessionManager.get();
        String deviceId = RequestUtil.getDeviceId(request);
        String deviceToken = RequestUtil.getDeviceToken(request);
        if (StrUtil.isEmpty(deviceId) || StrUtil.isEmpty(deviceToken) || ObjectUtil.isNull(session)) {
            return true;
        }
        userDeviceService.set(new UserDeviceDTO(deviceId, deviceToken, session.getData().getId()));
        return true;
    }
}
